package serverClient;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.Socket;

import orders.Customer;
import orders.IntockOrder;
import orders.Item;
import orders.Order;

/*
 * Client socket
 */
public class OrderClient extends Thread {

	private Socket socket;
	private String nameShop;
	private String nameCustomer;

	public OrderClient(String name) {
		super();
		this.nameShop = name;
	}

	public void setNameCustomer(String name) {
		this.nameCustomer = name;
	}

	/*
	 * Socket("localhost", 1992);
	 * step 1: Client send message name of customer to server.
	 * step 2: Client receive object Customer from Server
	 * step 3: Client add Order to customer and print order to console
	 * step 4: Client send object customer to server
	 */
	public void run() {
		try {
			socket = new Socket("localhost", 1992);
			
			// step 1
			PrintStream ps = new PrintStream(socket.getOutputStream());
			ps.println(nameCustomer);
			
			//step 2
			ObjectInputStream ois = new ObjectInputStream(
					socket.getInputStream());
			
			Customer customer = (Customer) ois.readObject();
			
			if (customer != null) {
				// step 3
				addOrder(customer);
				
				// step 4
				ObjectOutputStream oos = new ObjectOutputStream(
						socket.getOutputStream());
				oos.writeObject(customer);
			}
		} catch (IOException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// Client add order to customer
	public void addOrder(Customer customer) {
		Order order = new IntockOrder(this.nameShop);

		Item item1 = new Item("milk", 6500, 0, 3, "box");
		Item item2 = new Item("coffee", 2000, 0, 20, "box");
		Item item3 = new Item("banana", 10000, 7.0, 3, "kg");
		Item item4 = new Item("tomato", 20000, 10, 3, "kg");

		order.addItem(item1);
		order.addItem(item2);
		order.addItem(item3);
		order.addItem(item4);

		customer.addOrder(order);
		
		// Print order to console
		order.getPrice();
	}
}
